﻿// 
// DotNetNuke® - http://www.dotnetnuke.com
// Copyright (c) 2002-2011
// by DotNetNuke Corporation
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.


using System;

using DotNetNuke;
using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;
using System.Globalization;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System.Text;
using System;
using System.IO;

using ServiceReference1;
using System.Data;

namespace Triax.Modules.CSDLAnhHien
{
    /// -----------------------------------------------------------------------------
    /// <summary>
    /// The EditCSDLAnhHien class is used to manage content
    /// </summary>
    /// <remarks>
    /// </remarks>
    /// <history>
    /// </history>
    /// -----------------------------------------------------------------------------
    partial class EditCSDLAnhHien : PortalModuleBase
    {

        #region Private Members

        private int ItemId = Null.NullInteger;
        int level = -1;
        #endregion

        #region Event Handlers

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Page_Load runs when the control is loaded
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------
        protected void Page_Load(System.Object sender, System.EventArgs e)
        {
            try
            {

                // this.Control.Visible = false;

                //If this is the first visit to the page, bind the role data to the datalist
                if (Page.IsPostBack == false)
                {
                    BindThang();
                    ShowValue();
                 BindKyBaoCao();
                 BindCSDL();
                 txtThoigian1.Text = new DateTime(DateTime.Now.Year, 1, 1).ToString("dd/MM/yyyy");
                 txtThoigian2.Text = new DateTime(DateTime.Now.Year, 12, 31, 23, 59, 59).ToString("dd/MM/yyyy");
                    this.EnableViewState = true;

                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// cmdCancel_Click runs when the cancel button is clicked
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------
        protected void cmdCancel_Click(System.Object sender, System.EventArgs e)
        {
            try
            {
                this.Response.Redirect(Globals.NavigateURL(this.TabId), true);
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// cmdDelete_Click runs when the delete button is clicked
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------
       

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// cmdUpdate_Click runs when the update button is clicked
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------
        protected void cmdUpdate_Click(System.Object sender, System.EventArgs e)
        {
            ServiceReference1.BIPortalClient client = new ServiceReference1.BIPortalClient();

          //  ServiceReference1.BIPortalClient client = new BIPortalClient();
            string _DBName = "HuyHoangCenter";
            /*THONG TIN TONG THE*/
            /* 
               try
               {
                   client.ClientCredentials.Windows.ClientCredential.UserName = "other";
                   client.ClientCredentials.Windows.ClientCredential.Password = "123";
                   DateTime now = DateTime.Now;

                   string xml = client.ThongTinTongTheOut(_DBName, now.AddDays(-1), now, false);
             * //decimal[] result = client.KPITyLeLoiNhuanOut(_DBName, now.AddDays(-1), now);
                   Stream stream = StringToStream(xml);
                   //Phải đọc qua dataset, qua table trực tiếp k được
                   DataSet ds = new DataSet();
                   ds.ReadXml(stream);
                   DataTable dt = ds.Tables[0];

                   foreach (DataRow row in dt.Rows)
                   {
                       string key = "";
                       string values = "";
                       decimal value = (decimal)0;
                       if (row != null)
                       {
                           if (row["Key"] is string)
                               key = row["Key"].ToString();
                           if (row["Value"] is string)
                               try
                               {

                                   values = (string)(row["Value"]);
                                   values = values.Replace(".", ",");
                                   value = Convert.ToDecimal(values);
                                   //  Response.Write("<br/>" + value);
                               }
                               catch (Exception) { }
                       }

                       switch (key)
                       {
                           case "TM":
                               ucDigitalNumberTienMat.Text = String.Format("{0:### ### ### ###}", value);

                               break;
                           case "TGNH":
                               ucDigitalNumberTienGuiNganHang.Text = String.Format("{0:### ### ### ###}", value);
                               break;
                           case "GVHH":
                               ucDigitalNumberHangHoa.Text = String.Format("{0:### ### ### ###}", value);
                               break;
                           case "CNPThu":
                               ucDigitalNumberPhaiThu.Text = String.Format("{0:### ### ### ###}", value);
                               break;
                           case "CNPTra":
                               ucDigitalNumberPhaiTra.Text = String.Format("{0:### ### ### ###}", value);
                               break;
                           case "TT":
                               ucDigitalNumberTongThu.Text = String.Format("{0:### ### ### ###}", value);
                               break;
                           case "TC":
                               ucDigitalNumberTongChi.Text = String.Format("{0:### ### ### ###}", value);
                               break;
                           case "TNV":
                               ucDigitalNumberThuNguonVon.Text = String.Format("{0:### ### ### ###}", value);
                               break;
                           case "TK":
                               ucDigitalNumberThuKhac.Text = String.Format("{0:### ### ### ###}", value);
                               break;
                           case "TBH":
                               ucDigitalNumberThuBanHang.Text = String.Format("{0:### ### ### ###}", value);
                               break;
                           case "CK":
                               ucDigitalNumberChiKhac.Text = String.Format("{0:### ### ### ###}", value);
                               break;
                           case "CPHD":
                               ucDigitalNumberTongChiPhiHoatDong.Text = String.Format("{0:### ### ### ###}", value);
                               break;
                           case "CPSX":
                               ucDigitalNumberChiPhiSanXuat.Text = String.Format("{0:### ### ### ###}", value);
                               break;
                           case "CTNV":
                               ucDigitalNumberChiNguonVon411.Text = String.Format("{0:### ### ### ###}", value);
                               break;
                           case "CMH":
                               ucDigitalNumberChiMuaHang.Text = String.Format("{0:### ### ### ###}", value);
                               break;
                           case "LG":
                               ucDigitalNumberLaiGop.Text = String.Format("{0:### ### ### ###}", value);
                               break;
                           case "DSBB":
                               ucDigitalNumberDoanhSoBanBuon.Text = String.Format("{0:### ### ### ###}", value);
                               break;
                           case "DSBL":
                               ucDigitalNumberDoanhSoBanLe.Text = String.Format("{0:### ### ### ###}", value);
                               break;
                           //
                           case "DSSBBuon":
                               ucDoanhSoBanBuonSach.Text = String.Format("{0:### ### ### ###}", value);
                               break;
                           case "DSSBLe":
                               ucDoanhSoBanLeSach.Text = String.Format("{0:### ### ### ###}", value);
                               break;
                           case "DSVPPBBuon":
                               ucDoanhSoBanBuonHangKhac.Text = String.Format("{0:### ### ### ###}", value);
                               break;
                           case "DSVPPLe":
                               ucDoanhSoBanLeHangKhac.Text = String.Format("{0:### ### ### ###}", value);
                               break;
                           case "LaiBB":
                               ucDigitalNumberLaiGopBanBuon.Text = String.Format("{0:### ### ### ###}", value);
                               break;
                           case "LaiBL":
                               ucDigitalNumberLaiGopBanLe.Text = String.Format("{0:### ### ### ###}", value);
                               break;
                           //
                           case "LTCP":
                               ucDigitalNumberLaiTruChiPhi.Text = String.Format("{0:### ### ### ###}", value);
                               break;
                           case "TTNGTGT":
                               ucDigitalNumberThueThuNhap.Text = String.Format("{0:### ### ### ###}", value);
                               break;
                           case "LR":
                               ucDigitalNumberLoiNhuanThuc.Text = String.Format("{0:### ### ### ###}", value);
                               break;
                           case "NVKD":
                               ucDigitalNumberNguonVon.Text = String.Format("{0:### ### ### ###}", value);
                               break;
                           default:
                               break;
                       }
                   }
                   // dtStart = new System.DateTime(2014, 5, 1);

                   client.Close();
               }
               catch (Exception ex)
               {
                   Response.Write(ex.Message);
               }
               finally
               {
                   client.Close();
               }
             */

            /*KPI TY LE LOI NHUAN / TONG VON DAU THU */
            /*  
            try
               {
                   client.ClientCredentials.Windows.ClientCredential.UserName = "other";
                   client.ClientCredentials.Windows.ClientCredential.Password = "123";
                   DateTime now = DateTime.Now;

             //      string xml = client.ThongTinTongTheOut(_DBName, now.AddDays(-1), now, false);
              decimal[] result = client.KPITyLeLoiNhuanOut(_DBName, now.AddDays(-1), now);
              decimal lai = result[0];
              decimal tongVonDauTu = result[1];
              Response.Write("tongVonDauTu: " + tongVonDauTu + " lai " + lai);
                 //  Stream stream = StringToStream(xml);
                   //Phải đọc qua dataset, qua table trực tiếp k được
              }catch
              {

              } 
            */
            /*KPI TY LE LOI NHUAN / TONG VON DAU THU */

            /*
            try
            {
                client.ClientCredentials.Windows.ClientCredential.UserName = "other";
                client.ClientCredentials.Windows.ClientCredential.Password = "123";
                DateTime now = DateTime.Now;
                string xml = client.KPIBienDongDoanhSoBanHangOut(_DBName, now.AddDays(-1), now);
                
               
                  Stream stream = StringToStream(xml);
                  DataSet ds = new DataSet();
                  ds.ReadXml(stream);
                  DataTable dt = ds.Tables[0];
                
                  foreach (DataRow row in dt.Rows)
                  {
                      string key = "";
                      string values = "";
                      decimal value = (decimal)0;
                     // Row: Name, Month,Year,Amount
                      if (row != null)
                      {
                          if (row["Key"] is string)
                              key = row["Key"].ToString();
                          if (row["Value"] is string)
                              try
                              {

                                  values = (string)(row["Value"]);
                                  values = values.Replace(".", ",");
                                  value = Convert.ToDecimal(values);
                                  //  Response.Write("<br/>" + value);
                              }
                              catch (Exception) { }
                      }
                  }
                //Phải đọc qua dataset, qua table trực tiếp k được
            }
            catch
            {

                
            }
            */
            /*Vòng quay hàng tồn kho*/

             
            /*
            try
               {
                   client.ClientCredentials.Windows.ClientCredential.UserName = "other";
                   client.ClientCredentials.Windows.ClientCredential.Password = "123";
                   DateTime now = DateTime.Now;

             //      string xml = client.ThongTinTongTheOut(_DBName, now.AddDays(-1), now, false);
                decimal[] result = client.KPIVongQuayHangTonKhoOut(_DBName, now.AddDays(-1), now);
              decimal lai = result[0];
              decimal tongVonDauTu = result[1];
              Response.Write("tongVonDauTu: " + tongVonDauTu + " lai " + lai);
                 //  Stream stream = StringToStream(xml);
                   //Phải đọc qua dataset, qua table trực tiếp k được
              }catch
              {

              } 
            */
/**Biến động công nợ phải thu*/

            /*
            try
            {
                client.ClientCredentials.Windows.ClientCredential.UserName = "other";
                client.ClientCredentials.Windows.ClientCredential.Password = "123";
                DateTime now = DateTime.Now;
                string xml = client.BienDongTaiKhoanOut(_DBName, now.AddMonths(-1), now, "131", 3);
                
               
                  Stream stream = StringToStream(xml);
                  DataSet ds = new DataSet();
                  ds.ReadXml(stream);
                  DataTable dt = ds.Tables[0];
                  string vl = "";
                  foreach (DataRow row in dt.Rows)
                  {
                      string key = "";
                      string values = "";
                      decimal value = (decimal)0;
                     // Row: Name, Month,Year,Amount
                      if (row != null)
                      {
                          if (row["Key"] is string)
                              key = row["Key"].ToString();
                          if (row["Value"] is string)
                              try
                              {

                                  values = (string)(row["Value"]);
                                  values = values.Replace(".", ",");
                                  value = Convert.ToDecimal(values);
                                  //  Response.Write("<br/>" + value);
                                  vl += "Key: " + key + " values : " + value + "<br/>";
                              }
                              catch (Exception) { }
                      }
                  }
                  Response.Write("<br/>" + vl);
                //Phải đọc qua dataset, qua table trực tiếp k được
            }
            catch (Exception exx)
            {

                Response.Write("<br/>" + exx.ToString());
            }
              */
            // Cái cuối cùng là Nhật ký thu chi
            string vl = "";
            try
            {
                client.ClientCredentials.Windows.ClientCredential.UserName = "other";
                client.ClientCredentials.Windows.ClientCredential.Password = "123";
                DateTime now = DateTime.Now;
                string xml = client.NhatKyThuOrChiOut(_DBName, now.AddMonths(-1), now, true);


                Stream stream = StringToStream(xml);
                DataSet ds = new DataSet();
                ds.ReadXml(stream);
                DataTable dt = ds.Tables[0]; ;
             
                //Phải đọc qua dataset, qua table trực tiếp k được
              
               //  ds.ReadXml(stream);
               //DataTable dt = ds.Tables[0];
              
                foreach (DataRow row in dt.Rows)
                {
                    string key = "";
                    string values = "";
                    decimal value = (decimal)0;
                    string   MaDoiTuong = "";
string   TenDoiTuong = "";
string   NgayGhiSo = "";
string   So = "";
string   Ngay = "";
string   DienGiai = "";
string   SoHieuTaiKhoanNo = "";
string   SoHieuTaiKhoanCo = "";
string GiaTri = "";

                    // Row: Name, Month,Year,Amount
                    if (row != null)
                    {
                        if (row["MaDoiTuong"] is string)
                            MaDoiTuong = row["MaDoiTuong"].ToString();

                        if (row["TenDoiTuong"] is string)
                            TenDoiTuong = row["TenDoiTuong"].ToString();

                        if (row["NgayGhiSo"] is string)
                            TenDoiTuong = row["NgayGhiSo"].ToString();
                        So = row["So"].ToString();
                        Ngay = row["Ngay"].ToString();
                        DienGiai = row["DienGiai"].ToString();
                        SoHieuTaiKhoanNo = row["SoHieuTaiKhoanNo"].ToString();
                        SoHieuTaiKhoanCo = row["SoHieuTaiKhoanCo"].ToString();
                        GiaTri = row["GiaTri"].ToString();
                        vl += "MaDoiTuong: " + MaDoiTuong + " TenDoiTuong: " + TenDoiTuong + " So " + So + " Ngay " + Ngay + " DienGiai: " + DienGiai + " SoHieuTaiKhoanNo: " + SoHieuTaiKhoanNo + " SoHieuTaiKhoanCo : " + SoHieuTaiKhoanCo + " GiaTri : " + GiaTri + "<br/>";
                    }
                }
                thongbao.Text = Server.HtmlDecode(vl);
                //Phải đọc qua dataset, qua table trực tiếp k được
            }
            catch (Exception exx)
            {

                thongbao.Text = exx.ToString();
            }


//            try
//            {
//                DateTime ngayBatDau = DateTime.Parse(txtThoigian1.Text);
//                DateTime ngayKetThuc = DateTime.Parse(txtThoigian2.Text);
//                DateTime now = DateTime.Now;


//                //Button2_Click(sender, e);
//                // lay du lieu vao day Huyhoang
//                string ngaybatdau = txtThoigian1.Text;
//                string ngayketthuc = txtThoigian2.Text;
//                string songay = drThang.SelectedValue;
//                client.ClientCredentials.Windows.ClientCredential.UserName = "other";
//                client.ClientCredentials.Windows.ClientCredential.Password = "123";
//                DateTime dtStart = DateTime.Parse(ngaybatdau+" 00:00:00");
//                DateTime dtEnd = DateTime.Parse(ngayketthuc + " 23:59:00");
//            //      Response.Write("<br/>startdate: " + String.Format("{0:MM/dd/yy H:mm:ss zzz}", dtStart));
//        //        Response.Write("<br/>dtEnd: " + String.Format("{0:MM/dd/yy H:mm:ss zzz}", dtEnd));
//                bool check = false;
//                if (tinhcongno.Checked)
//                {
//                    check = true;
//                }
//                string xml = client.ThongTinTongThe(drChonCSDL.SelectedValue, dtStart, dtEnd, check);
//                Stream stream = StringToStream(xml);
//                DataSet ds = new DataSet();
//                ds.ReadXml(stream);
         

//                //Reading XML file and copying to dataset

//                DataTable dt = ds.Tables["ThongTinTongThe"];
//              //  GridView1.DataSource = dt;
//              //  GridView1.DataBind();
//                foreach (DataRow row in dt.Rows)
//                {
//                    string key = "";
//                    string values = "";
//                    decimal value = (decimal)0;
//                    if (row != null)
//                    {
//                        if (row["Key"] is string)
//                            key = row["Key"].ToString();
//                        if (row["Value"] is string)
//                            try
//                            {
                               
//                                values = (string) (row["Value"]);
//                                values = values.Replace(".", ",");
//                                 value = Convert.ToDecimal(values);
//                              //  Response.Write("<br/>" + value);
//                            }
//                            catch (Exception) { }
//                    }

//                    switch (key)
//                    {
//                         case "TM":
//                            ucDigitalNumberTienMat.Text =  String.Format("{0:### ### ### ###}", value);
                           
//                            break;
//                        case "TGNH":
//                            ucDigitalNumberTienGuiNganHang.Text =  String.Format("{0:### ### ### ###}", value);
//                            break;
//                        case "GVHH":
//                            ucDigitalNumberHangHoa.Text =  String.Format("{0:### ### ### ###}", value);
//                            break;
//                        case "CNPThu":
//                            ucDigitalNumberPhaiThu.Text =  String.Format("{0:### ### ### ###}", value);
//                            break;
//                        case "CNPTra":
//                            ucDigitalNumberPhaiTra.Text =  String.Format("{0:### ### ### ###}", value);
//                            break;
//                        case "TT":
//                            ucDigitalNumberTongThu.Text =  String.Format("{0:### ### ### ###}", value);
//                            break;
//                        case "TC":
//                            ucDigitalNumberTongChi.Text =  String.Format("{0:### ### ### ###}", value);
//                            break;
//                        case "TNV":
//                            ucDigitalNumberThuNguonVon.Text =  String.Format("{0:### ### ### ###}", value);
//                            break;
//                        case "TK":
//                            ucDigitalNumberThuKhac.Text =  String.Format("{0:### ### ### ###}", value);
//                            break;
//                        case "TBH":
//                            ucDigitalNumberThuBanHang.Text =  String.Format("{0:### ### ### ###}", value);
//                            break;
//                        case "CK":
//                            ucDigitalNumberChiKhac.Text =  String.Format("{0:### ### ### ###}", value);
//                            break;
//                        case "CPHD":
//                            ucDigitalNumberTongChiPhiHoatDong.Text =  String.Format("{0:### ### ### ###}", value);
//                            break;
//                        case "CPSX":
//                            ucDigitalNumberChiPhiSanXuat.Text =  String.Format("{0:### ### ### ###}", value);
//                            break;
//                        case "CTNV":
//                            ucDigitalNumberChiNguonVon411.Text =  String.Format("{0:### ### ### ###}", value);
//                            break;
//                        case "CMH":
//                            ucDigitalNumberChiMuaHang.Text =  String.Format("{0:### ### ### ###}", value);
//                            break;
//                        case "LG":
//                            ucDigitalNumberLaiGop.Text =  String.Format("{0:### ### ### ###}", value);
//                            break;
//                        case "DSBB":
//                            ucDigitalNumberDoanhSoBanBuon.Text =  String.Format("{0:### ### ### ###}", value);
//                            break;
//                        case "DSBL":
//                            ucDigitalNumberDoanhSoBanLe.Text =  String.Format("{0:### ### ### ###}", value);
//                            break;
//                        //
//                        case "DSSBBuon":
//                            ucDoanhSoBanBuonSach.Text =  String.Format("{0:### ### ### ###}", value);
//                            break;
//                        case "DSSBLe":
//                            ucDoanhSoBanLeSach.Text =  String.Format("{0:### ### ### ###}", value);
//                            break;
//                        case "DSVPPBBuon":
//                            ucDoanhSoBanBuonHangKhac.Text =  String.Format("{0:### ### ### ###}", value);
//                            break;
//                        case "DSVPPLe":
//                            ucDoanhSoBanLeHangKhac.Text =  String.Format("{0:### ### ### ###}", value);
//                            break;
//                        case "LaiBB":
//                            ucDigitalNumberLaiGopBanBuon.Text =  String.Format("{0:### ### ### ###}", value);
//                            break;
//                        case "LaiBL":
//                            ucDigitalNumberLaiGopBanLe.Text =  String.Format("{0:### ### ### ###}", value);
//                            break;
//                        //
//                        case "LTCP":
//                            ucDigitalNumberLaiTruChiPhi.Text =  String.Format("{0:### ### ### ###}", value);
//                            break;
//                        case "TTNGTGT":
//                            ucDigitalNumberThueThuNhap.Text =  String.Format("{0:### ### ### ###}", value);
//                            break;
//                        case "LR":
//                            ucDigitalNumberLoiNhuanThuc.Text =  String.Format("{0:### ### ### ###}", value);
//                            break;
//                        case "NVKD":
//                            ucDigitalNumberNguonVon.Text =  String.Format("{0:### ### ### ###}", value);
//                            break;
//                        default:
//                            break;
//                    }
//                }
//                // dtStart = new System.DateTime(2014, 5, 1);
            
//client.Close();
//            }
//        catch
//    {}
    }
        public static Stream StringToStream(string str)
        {
            MemoryStream stream = new MemoryStream();
            StreamWriter writer = new StreamWriter(stream);
            writer.Write(str);
            writer.Flush();
            stream.Position = 0;
            return stream;
        }
        public string showvalue(string v)
        {
            string res = "";
            if (v == "-1")
                return "";

            res = Convert.ToSingle(v).ToString();
            return res;

        }
        public bool validate()
        {
            bool res = true;
            string mess = "";
            string startDate = txtThoigian1.Text;
            string endDate = txtThoigian2.Text;
            if (startDate != "")
            {
                try
                {
                    DateTime d1 = DateTime.Parse(startDate);
                }
                catch
                {
                    res = false;
                    mess +=" Lỗi Ngày tháng (Từ ngày)";
                }
            }
            if (endDate != "")
            {
                try
                {
                    DateTime d1 = DateTime.Parse(endDate);
                }
                catch
                {
                    res = false;
                    mess += " Lỗi Ngày tháng (đến ngày)";
                }
            }

            Error.Text = mess;
            

            return res;
        }

        public string getTitle()
        {
            string res = "";
            
            string startDate = txtThoigian1.Text;
            string endDate = txtThoigian2.Text;

            if (startDate.Length > 0)
            {
                if (endDate.Length == 0)
                {
                    res = "TỔNG HỢP VỤ VIỆC NGÀY: " + startDate + "";
                }
                else
                {
                    if ((startDate.Length > 0) && (endDate.Length > 0))
                    {
                        res = " TỔNG HỢP VỤ VIỆC TỪ NGÀY " + startDate + " ĐẾN NGÀY " + endDate + "";
                    }

                }
            }
            return res;
        }
        public string getCond()
        {
            string cond = "";
            return cond;
        }

        public string getCondcongty()
        {
            string cond = "";
       
            return cond;
        }
            
        protected void getTinhThanh()
        {

            //   RecursiveFillTree2(p, 0);

        }

       



        #endregion

       

       
     

        protected void BindThang()
        {
            drThang.Items.Clear();

            for (int i = 5; i < 10; i++)
            {
                drThang.Items.Add(new ListItem(i.ToString(),i.ToString()));
            }
            
            //   drLoaibaocao.SelectedValue = ModuleDepartmentConst._ON.ToString();
            drThang.DataBind();
        }


        protected void BindCSDL()
        {
            string[] datas = new string[] { "ThanhVinh2Center", "ThanhVinh1Center", "BachKhoaCenter", "HuyHoangCenter", "HuyHoangSGCenter" };
            string[] datas2 = new string[] { "Thành vinh 2", "Thành vinh 1", "Bách khoa", "Ngọc hà", "Sài gòn" };
            drChonCSDL.Items.Clear();

            for (int i = 0; i < Triax.Modules.Department.ModuleDepartmentConst.datasTitie.Length; i++)
            {
                drChonCSDL.Items.Add(new ListItem(Triax.Modules.Department.ModuleDepartmentConst.datasTitie[i], Triax.Modules.Department.ModuleDepartmentConst.datas[i]));
            }


            //   drLoaibaocao.SelectedValue = ModuleDepartmentConst._ON.ToString();
            drChonCSDL.DataBind();
        }


          protected void BindKyBaoCao()
        {
            drKyBaoCao.Items.Clear();
              string [] datas = new string[] {"Cả năm","Quý I","Quý II","Quý III","Quý IV","Tháng 1","Tháng 2","Tháng 3","Tháng 4","Tháng 5","Tháng 6","Tháng 7","Tháng 8","Tháng 9","Tháng 10","Tháng 11","Tháng 12","Tuần gần nhất","Tháng này","Hôm qua","Hôm nay","Tùy chọn"};

            for (int i = 0; i < datas.Length; i++)
            {
                drKyBaoCao.Items.Add(new ListItem(datas[i],datas[i]));
            }
            
            //   drLoaibaocao.SelectedValue = ModuleDepartmentConst._ON.ToString();
            drKyBaoCao.DataBind();
        }

        protected void ShowValue()
        {
            drShow.Items.Clear();


            drShow.Items.Add(new ListItem("--------", "0"));
                drShow.Items.Add(new ListItem("Hiện", "1"));
                drShow.Items.Add(new ListItem("Ẩn", "2"));
          

            //   drLoaibaocao.SelectedValue = ModuleDepartmentConst._ON.ToString();
            drShow.DataBind();
        }

        
        // đổi ra số la mã
        public string ToRoman(int number)
        {
            if (-9999 >= number || number >= 9999)
            {
                return "";
            }

            if (number == 0)
            {
                return "";
            }

            StringBuilder sb = new StringBuilder(10);

            if (number < 0)
            {
                sb.Append('-');
                number *= -1;
            }

            string[,] table = new string[,] { 
        { "", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX" }, 
        { "", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC" }, 
        { "", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM" },
        { "", "M", "MM", "MMM", "M(V)", "(V)", "(V)M", 
                                          "(V)MM", "(V)MMM", "M(X)" } 
    };

            for (int i = 1000, j = 3; i > 0; i /= 10, j--)
            {
                int digit = number / i;
                sb.Append(table[j, digit]);
                number -= digit * i;
            }

            return sb.ToString();
        }
       
       
         private class ChartData
         {
             public String Mounth { get; set; }
             public Double Money { get; set; }
             public String Key { get; set; }
             public int Values { get; set; }

             public static List<ChartData> CreateCompanyList1()
             {
                 List<ChartData> company1 = new List<ChartData>();
                 company1.Add(new ChartData() { Mounth = "January", Money = 100 });
                 company1.Add(new ChartData() { Mounth = "February", Money = 120 });
                 company1.Add(new ChartData() { Mounth = "March", Money = 140 });
                 return company1;
             }

             public static List<ChartData> CreateCompanyList2()
             {
                 List<ChartData> company2 = new List<ChartData>();
                 company2.Add(new ChartData() { Mounth = "January", Money = 80 });
                 company2.Add(new ChartData() { Mounth = "February", Money = 160 });
                 company2.Add(new ChartData() { Mounth = "March", Money = 130 });
                 return company2;
             }
         }

         protected void drKyBaoCao_SelectedIndexChanged(object sender, System.EventArgs e)
         {
             ServiceReference1.BIPortalClient client = new ServiceReference1.BIPortalClient();

             DateTime ngayBatDau = DateTime.Now;
             //DateTime.Parse(txtThoigian1.Text);
             DateTime ngayKetThuc = DateTime.Now; //DateTime.Parse(txtThoigian2.Text);
             DateTime now = DateTime.Now;
             switch (drKyBaoCao.SelectedItem.Text)
             {
                 case "Hôm nay":
                     txtThoigian1.Enabled = true;
                     txtThoigian1.Enabled = true;
                     ngayBatDau = new DateTime(now.Year, now.Month, now.Day, 0, 0, 0);
                     ngayKetThuc = new DateTime(now.Year, now.Month, now.Day, 23, 59, 59);
                     break;
                 case "Hôm qua":
                     txtThoigian1.Enabled = false;
                     txtThoigian2.Enabled = false;
                     ngayBatDau = new DateTime(now.Year, now.Month, now.Day, 0, 0, 0).AddDays(-1);
                     ngayKetThuc = new DateTime(now.Year, now.Month, now.Day, 23, 59, 59).AddDays(-1);
                     break;
                 case "Tuần gần nhất":
                     txtThoigian1.Enabled = false;
                     txtThoigian2.Enabled = false;
                     ngayBatDau = new DateTime(now.Year, now.Month, now.Day, 0, 0, 0).AddDays(-7);
                     ngayKetThuc = new DateTime(now.Year, now.Month, now.Day, 23, 59, 59);
                     break;
                 case "Tháng này":
                     txtThoigian1.Enabled = false;
                     txtThoigian2.Enabled = false;
                     ngayBatDau = new DateTime(now.Year, now.Month, 1, 0, 0, 0);
                     ngayKetThuc = new DateTime(now.Year, now.Month, System.DateTime.DaysInMonth(now.Year, now.Month), 23, 59, 59);
                     break;
                 case "Tùy chọn":
                     txtThoigian1.Enabled = true;
                     txtThoigian2.Enabled = true;
                     try
                     {
                         if (drChonCSDL.Text == "")
                         {
                             Error.Text = "Cần chọn Chi nhánh - CSDL";
                             drChonCSDL.Focus();
                             return;
                         }
                         client.ClientCredentials.Windows.ClientCredential.UserName = "other";
                         client.ClientCredentials.Windows.ClientCredential.Password = "123";
                         DateTime dtThoiDiemKhoaSoGanNhat = client.GetThoiDiemKhoaSoGanNhatOut(drChonCSDL.Text, DateTime.Now);
                         //ThoiDiemKhoaSo thoiDiemKhoaSoGanNhat = new ThoiDiemKhoaSo(dtThoiDiemKhoaSoGanNhat.Rows[0]);
                         client.Close();
                         ngayBatDau = dtThoiDiemKhoaSoGanNhat;
                     }
                     catch (Exception ex)
                     {
                         Error.Text = (ex.ToString());
                     }
                     ngayKetThuc = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 23, 59, 59);
                     break;
                 case "Cả năm":
                     txtThoigian1.Enabled = false;
                     txtThoigian2.Enabled = false;
                     ngayBatDau = new DateTime(DateTime.Now.Year, 1, 1);
                     ngayKetThuc = new DateTime(DateTime.Now.Year, 12, 31, 23, 59, 59);
                     break;
                 case "Quý I":
                     txtThoigian1.Enabled = false;
                     txtThoigian2.Enabled = false;
                     ngayBatDau = new DateTime(DateTime.Now.Year, 1, 1);
                     ngayKetThuc = new DateTime(DateTime.Now.Year, 3, 31, 23, 59, 59);
                     break;
                 case "Quý II":
                     txtThoigian1.Enabled = false;
                     txtThoigian2.Enabled = false;
                     ngayBatDau = new DateTime(DateTime.Now.Year, 4, 1);
                     ngayKetThuc = new DateTime(DateTime.Now.Year, 6, 30, 23, 59, 59);
                     break;
                 case "Quý III":
                     txtThoigian1.Enabled = false;
                     txtThoigian2.Enabled = false;
                     ngayBatDau = new DateTime(DateTime.Now.Year, 7, 1);
                     ngayKetThuc = new DateTime(DateTime.Now.Year, 9, 30, 23, 59, 59);
                     break;
                 case "Quý IV":
                     txtThoigian1.Enabled = false;
                     txtThoigian2.Enabled = false;
                     ngayBatDau = new DateTime(DateTime.Now.Year, 10, 1);
                     ngayKetThuc = new DateTime(DateTime.Now.Year, 12, 31, 23, 59, 59);
                     break;
                 default:
                     try
                     {
                         txtThoigian1.Enabled = false;
                         txtThoigian2.Enabled = false;
                         string strThang = ((string)drKyBaoCao.SelectedItem.Text).Substring(((string)(drKyBaoCao.SelectedItem.Text)).LastIndexOf(" "));
                         int thang = int.Parse(strThang);

                         ngayBatDau = new DateTime(DateTime.Now.Year, thang, 1);
                         ngayKetThuc = new DateTime(DateTime.Now.Year, thang,
                                         DateTime.DaysInMonth(DateTime.Now.Year, thang), 23, 59, 59);
                     }
                     catch (Exception ex)
                     {
                         throw new Exception(ex.Message);
                     }
                     break;
             }
             client.Close();
             txtThoigian1.Text = ngayBatDau.ToString("dd/MM/yyyy");
             txtThoigian2.Text = ngayKetThuc.ToString("dd/MM/yyyy");
           

         }

         public static string Decimal2Money(decimal money)
         {
             try
             {
                 string ret = "";
                 bool soAm = false;
                 if (money < 0)
                 {
                     money = -money;
                     soAm = true;
                 }

                 double real = Math.Floor((double)money);
                 while (real >= 1000)
                 {
                     string tem = ((int)(real % 1000)).ToString();
                     if (tem.Length == 1) tem = "00" + tem;
                     else if (tem.Length == 2) tem = "0" + tem;
                     ret = tem + "." + ret;
                     real = Math.Floor(real / 1000);
                 }
                 ret = ((int)(real % 1000)).ToString() + "." + ret;
                 if (ret.EndsWith(".")) ret = ret.Substring(0, ret.Length - 1);
                 if (soAm) ret = "-" + ret;
                 return ret;
             }

             catch (Exception ex)
             {

             }
             return "";
         }

         protected void baocao_Click(object sender, System.EventArgs e)
         {
             string str2 = "";
             str2 +="<table class=\"table-fill\">";
  str2 += "<thead>";
  str2 += "<tr>";
  //str2 += "<th class=\"text-left\">Month</th>";
 
  //str2 += "</thead>";
  //str2 += "<tbody class=\"table-hover\">";
  //str2 += "<tr>";
  //str2 += "<td class=\"text-left\">January</td>";
  //str2 += "<td class=\"text-left\">$ 50,000.00</td>";
  //str2 += "</tr>";

  //drChonCSDL.Items.Add(new ListItem(Triax.Modules.Department.ModuleDepartmentConst.datasTitie[i], Triax.Modules.Department.ModuleDepartmentConst.datas[i]));
             ServiceReference1.BIPortalClient client = new ServiceReference1.BIPortalClient();
             string[] datas = Triax.Modules.Department.ModuleDepartmentConst.datas;
             string[] datasTitie = Triax.Modules.Department.ModuleDepartmentConst.datasTitie;
             string[] color = new string[] { "#FF0000", "#FFFF00", "#00FF00", "color: #00FFFF ", "#0000FF" };
             for(int i=0; i<datasTitie.Length; i++)
             {
                 str2 += "<th class=\"text-left\">"+ datasTitie[i] + "</th>";
             }
             //str2 += "<th class=\"text-left\">Sales</th>";
             str2 += "</tr>";
             str2 += "</thead>";
             str2 += "<tbody class=\"table-hover\">";
             // End header
             //  ServiceReference1.BIPortalClient client = new BIPortalClient();
             string _DBName = drChonCSDL.SelectedValue;
             DateTime tungay = DateTime.Now;
             DateTime denngay = DateTime.Now;
             try
             {
                 tungay = DateTime.Parse(convertdate(txtThoigian1.Text));
             }
             catch
             {
                 tungay = DateTime.Now.AddDays(-1);
             }
             try
             {
                 denngay = DateTime.Parse(convertdate(txtThoigian2.Text));
                 denngay = new DateTime(denngay.Year, denngay.Month, denngay.Day, 23, 59, 59);
             }
             catch
             {
                 denngay = DateTime.Now;
             }
             string alldata = "";
             string strlai = "";
             string strtonvon = "";
             string strchiso = "";
             try
             {
                 client.ClientCredentials.Windows.ClientCredential.UserName = "other";
                 client.ClientCredentials.Windows.ClientCredential.Password = "123";
                 DateTime now = DateTime.Now;
                 for (int i = 0; i < datas.Length; i++)
                 {
                 
                 //      string xml = client.ThongTinTongTheOut(_DBName, now.AddDays(-1), now, false);
                     decimal[] result = client.KPIVongQuayHangTonKhoOut(datas[i], tungay, denngay);
                 decimal lai = result[0];
                 decimal tongVonDauTu = result[1];
                // giavonbanhang.Text = String.Format("{0:### ### ### ###}", tongVonDauTu); //.ToString();
                // hangtonkho.Text = String.Format("{0:### ### ### ###}", lai); //.ToString();
                 //chisotonkho.Text = String.Format("{0:0.00}",(lai / tongVonDauTu)).ToString();
                 alldata += String.Format("{0:### ### ### ###}", tongVonDauTu) + ";" + String.Format("{0:### ### ### ###}", lai) + String.Format("{0:0.00}", (lai / tongVonDauTu)).ToString()+ "@";
                 strlai += String.Format("{0:### ### ### ###}", lai) + ";";
                 strtonvon += String.Format("{0:### ### ### ###}", tongVonDauTu) + ";";
                 strchiso += String.Format("{0:0.00}", (lai / tongVonDauTu)).ToString() + ";";
               //  str2 += "<th class=\"text-left\">" + datasTitie[i] + "</th>";
                 }

                 string[] chinhanhs = alldata.Split('@');
                 string[] strlais = strlai.Split(';');
                 string[] strtonvons = strtonvon.Split(';');
                 string[] strchisos = strchiso.Split(';');
                 str2 += "<tr>";
                 for (int i = 0; i < strtonvons.Length - 1; i++)
                 {

                     str2 += "<td class=\"text-left-red\"> <font color='red'>" + strlais[i] + "</font></td>";
                 }
                 str2 += "</tr>";
                 str2 += "<tr>";
                 for (int i = 0; i < strtonvons.Length-1; i++)
                 {

                     str2 += "<td class=\"text-left-green\"> <font color='green'>" + strtonvons[i] + "</font></td>";
                 }
                 str2 += "</tr>";
                 
                 str2 += "<tr>";
                 for (int i = 0; i < strtonvons.Length - 1; i++)
                 {

                     str2 += "<td class=\"text-left-blue\"><font color='blue'>" + strchisos[i] + "</font></td>";
                 }
                 str2 += "</tr>";
                 str2 += "</tr>";
                str2 += "</tbody>";
                str2 += "</table><br/>&nbsp;";
                str2 += "<table>";
                str2 += "   <tr>";
                str2 += "    <td bgcolor=\"red\">&nbsp;</td>";
                str2 += "<td>Giá vốn hàng bán</td>";
                str2 += "</tr>";
                str2 += "<tr>";
                str2 += "    <td bgcolor=\"green\">&nbsp;</td>";
                str2 += "<td >Hàng tồn kho</td>";
                str2 += "</tr>";
                str2 += "<tr>";
                str2 += "<td bgcolor=\"blue\">&nbsp;</td>";
                str2 += "<td>Chỉ số</td>";
                str2 += "  </tr>";
                str2 += "</table> ";
                string str = "";
                str += "<script type=\"text/javascript\">";
                str += "       google.charts.load('current', { 'packages': ['corechart'] });";
                str += "       google.charts.setOnLoadCallback(drawChart);";
                str += "       function drawChart() {";
                str += "";
                str += "           var data = google.visualization.arrayToDataTable([";

                str += "        [\"Chi nhánh\", \"Chỉ số\", { role: \"style\" } ]\n";
                for (int i = 0; i < datasTitie.Length; i++)
                {
                    str += ",['" + datasTitie[i] + "', " + strchisos[i] + "," + "'" + color[i] + "'" + "]";// dbs[i] + " doanh thu: " + result[i] + "<br/>";

                }
                //    str += "             ['Ngọc Hà', " + tyle.ToString() + "]";
                str += "            ";
                str += "           ]);";
                //str += "           var data2 = google.visualization.arrayToDataTable([";
                //str += "             ['Label', 'Value'],";
                //str += "             ['Thành Vinh', 60]";
                //str += "";
                //str += "           ]);";
                //str += "           var data3 = google.visualization.arrayToDataTable([";
                //str += "            ['Label', 'Value'],";
                //str += "            ['Sài gòn', 60]";
                //str += "";
                //str += "           ]);";
                //str += "";
                str += " var view = new google.visualization.DataView(data);";
                str += "      view.setColumns([0, 1,";
                str += "                       { calc: \"stringify\",";
                str += "                         sourceColumn: 1,";
                str += "                         type: \"string\",";
                str += "                         role: \"annotation\" },";
                str += "                       2]);";
                str += "";
                str += "      var options = {";
                str += "        title: \"Biểu đồ KPI chỉ số quay vòng tồn kho\",";
                str += "        width: 600,";
                str += "        height: 400,";
                str += "        bar: {groupWidth: \"95%\"},";
                str += "        legend: { position: \"none\" },";
                str += "      };";
                str += "           var chartvw =   $(window).width()/1.5;\n";
                str += "                          $(\"#piechart\").css({ \"margin-top\": 0, \"height\": 400 });\n"; ;
                str += "           var chart = new google.visualization.ColumnChart(document.getElementById('piechart'));";
                //str += "           var chart2 = new google.visualization.Gauge(document.getElementById('chart_div2'));";
                //str += "           var chart3 = new google.visualization.Gauge(document.getElementById('chart_div3'));";
                //str += "";
                str += "           chart.draw(view, options);";
                //str += "           chart2.draw(data2, options);";
                //str += "           chart3.draw(data3, options);";
                str += "";
                str += "          ";
                str += "       }";
                str += "    </script>";
                Literal2.Text = Server.HtmlDecode(str2);
                chart.Text = Server.HtmlDecode(str);
                 //Response.Write("tongVonDauTu: " + tongVonDauTu + " lai " + lai);
                 //ucDigitalNumberTienMat.Text = "tongVonDauTu: " + tongVonDauTu + " lai " + lai;
                 //  Stream stream = StringToStream(xml);
                 //Phải đọc qua dataset, qua table trực tiếp k được
             }
             catch (Exception ex)
             {
                 Literal2.Text = Server.HtmlDecode("Lỗi kết nối đến CSDL");
             }
         }

            
         public string convertdate(string date)
         {
             string res = "";
             string[] d = date.Split('/');
             if (d.Length > 2)
             {
                 res = d[1] + "/" + d[0] + "/" + d[2];
             }
             return res;

         }
}
}

